// ws_micro_shop/pages/userinfo/userinfo.js
const api = require('../../utils/api.js');
const app = getApp();
Page({
  data: {
    userInfo: {},
    time: '',
    theme: app.themeData,
    today: '',
    disable: true,
    imgUrl: app.imgUrl,
    isShow: false,
  },

  onLoad(options) {
    let userInfo = wx.getStorageSync('user_info');
    this.setData({
      userInfo,
      today: new Date()
        .toLocaleDateString()
        .split('/')
        .join('-'),
      time: userInfo.birthday || '',
      address: userInfo.address || '',
      name: userInfo.realname || '',
      mobile: userInfo.mobile || '',
      gender: userInfo.gender || '',
      disable: userInfo.mobile ? false : true,
    });
    wx.setNavigationBarTitle({
      title: '个人资料',
    })
    console.log(this.data.time);
  },
  onShow(){
    let that = this;
    // let usetype = wx.getStorageSync('usetype');
    // let resData = wx.getStorageSync('resPic');
    // let imgUrl;
    // if (resData) {
    //   imgUrl = JSON.parse(resData).url;
    // }
    // let user = this.data.userInfo;
    // if (usetype === 'avatar') {
    //   user.avatar_url = imgUrl;
    //   this.setData({
    //     userInfo: user,
    //   });
    // }
    wx.getSetting({
      success (res){
        if (!res.authSetting['scope.userInfo']) {
          that.setData({
            isShow: true,
          })
        } else {
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称
            wx.getUserInfo({
              success: function(res) {
                that.getuserinfo(res);
              }
            })
          }
        }
      }
    })
    
  },
  getuserinfo(res) {
    let that = this;
    let { userInfo } = that.data;
    app.ws_micro_shoplogin(1).then(resp => {
      if (res.errMsg === 'getUserInfo:ok') {
        const systemInfo = wx.getSystemInfoSync();
        app.ws_micro_shoprequest({
          url: api.passport.info,
          data: {
            user_info: JSON.stringify(res.userInfo),
            encrypted_data: res.encryptedData,
            iv: res.iv,
            brand: systemInfo.brand,
            model: systemInfo.model,
          },
          method: 'POST',
          success: function(res) {
            if (res.code === 0) {
              // wx.showToast({ title: '操作成功' });
              let data = res.data;
              userInfo.nickname = data.nickname;
              userInfo.avatar_url = data.avatar_url;
              userInfo.avatar_url = data.avatar_url;
              userInfo.gender = data.gender;
              wx.setStorageSync('user_info', userInfo);
              that.setData({
                userInfo,
                gender: userInfo.gender
              })
            }
          },
        });
      }
    })
  },
  today(){
    var data = new Date();
    var year = data.getFullYear();
    var month = data.getMonth() + 1;
    var day = data.getDate();
    return year+'-'+month+'-'+day;
  },
  pickGoodsAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        let src = res.tempFilePaths[0];
        let sceneName = 'square';
        let usetype = 'avatar';
        let url = 'utility/file/upload';
        if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
          url = app.util.url(url, { type: 'image', thumb: '0' });
        }
        wx.setStorage({
          key: 'uploadUrl',
          data: url,
        });
        wx.navigateTo({
          url: `/common/component/cropper/cropper?sceneName=${sceneName}&src=${src}&usetype=${usetype}`,
        });
      },
    });
  },
  save(e) {
    if (this.data.disable) {
      return;
    }
    let { userInfo, time } = this.data;
    let { name: realname, sex: gender, mobile, address} = e.detail.value;
    app.ws_micro_shoprequest({
      url: api.user.edit_info,
      data: {
        gender,
        realname,
        day: time,
        mobile,
        address,
        avatar: userInfo.avatar_url
      },
      method: 'POST',
      success: function(res) {
        if (res.code === 0) {
          userInfo.realname = realname;
          userInfo.gender = gender;
          userInfo.birthday = time;
          wx.setStorageSync('user_info', userInfo);
          wx.showModal({
            title: '提示',
            content: '保存成功',
            showCancel: false,
            success: t => {
              if (t.confirm) {
                wx.navigateBack();
              }
            },
          });
        } else {
          wx.showToast({
            title: '保存失败',
            icon: 'none',
          });
        }
      },
    });
  },

  pickDate(e) {
    this.setData({
      time: e.detail.value,
    });
  },

  input(e) {
    this.setData({
      [e.currentTarget.id]: e.detail.value,
    });
    if (this.data.mobile) {
      this.setData({
        disable: false,
      });
    } else {
      this.setData({
        disable: true,
      });
    }
  },
  
  onPullDownRefresh() {},

});
